package com.gitee.qdbp.general.common.biz.sms.service;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.general.common.api.sms.model.ISmsTemplate;
import com.gitee.qdbp.general.common.error.GeneralErrorCode;
import com.gitee.qdbp.tools.files.PathTools;
import com.gitee.qdbp.tools.http.HttpException;
import com.gitee.qdbp.tools.http.HttpTools;
import com.gitee.qdbp.tools.utils.ConvertTools;

/**
 * 南京飞拓短信服务接口<br>
 * http://www.jssms.cn/
 *
 * @author zhaohuihua
 * @version 160109
 */
// @Service // 这个Service在spring的xml文件中配置, 因为有些平台不需要短信功能
public class FeituoSmsService extends BaseSmsService {

    private static final Logger log = LoggerFactory.getLogger(FeituoSmsService.class);

    public FeituoSmsService() {
        this.properties = "settings/sms/sms.feituo.txt";
    }

    @Override
    @PostConstruct
    public void init() {
        super.init();
    }

    @Override
    public String send(String phone, ISmsTemplate template, Object... args) throws ServiceException {

        utils.check(phone, template.name());

        String msg = "Failed to send Short Message.";

        String host = config.getString("sms.service.url");
        String uri = config.getString("sms.send.uri");
        String url = PathTools.concat(host, uri);

        // method=sendMsg&username=JSM40001&scode=123456
        // &mobile=15951977097&content=@1@=李先生,@2@=您好,@3@=928371&msgtype=2&tempid=JSM4001-000
        StringBuilder text = new StringBuilder();
        for (int i = 0; i < args.length; i++) {
            if (i > 0) {
                text.append(",");
            }
            text.append("@").append(i + 1).append("@");
            text.append("=").append(args[i]);
        }

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("method", "sendMsg");
        params.put("username", config.getString("auth.username"));
        params.put("scode", config.getString("auth.password"));
        params.put("mobile", phone);
        params.put("content", text.toString());
        // params.put("msgtype", 2);
        params.put("tempid", config.getString("template." + template.name()));

        // 0#1#1, 返回值#提交计费条数#提交成功号码数
        String response;
        try {
            response = HttpTools.form.post(url, params);
        } catch (HttpException e) {
            log.error(msg + " HTTP request exception.", e);
            throw new ServiceException(GeneralErrorCode.SMS_SEND_ERROR);
        }

        String[] words = split(response.trim());
        String code = words[0];
        if (code == null || !code.equals(code)) {
            if (words.length == 3) {
                String desc = config.getString("resultcode.send." + code, false);
                log.error(msg + " result code is {} - {}", code, desc);
            } else {
                // 110#(敏感词A,敏感词B)
                String desc = config.getString("resultcode.send." + code, false);
                log.error(msg + " result code is {} - {} - {}", code, desc, words[1]);
            }
            throw new ServiceException(GeneralErrorCode.SMS_SEND_ERROR);
        }

        return null;
    }

    @Override
    public Double balances() throws ServiceException {

        String msg = "Failed to get sms balances.";

        String host = config.getString("sms.service.url");
        String uri = config.getString("sms.balances.uri");
        String url = PathTools.concat(host, uri);

        // method=getAmount&username=JSM40001&scode=123456
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("method", "getAmount");
        params.put("username", config.getString("auth.username"));
        params.put("scode", config.getString("auth.password"));

        // 0#9554, 0=成功, 9554=余额(955.40元)
        String response;
        try {
            response = HttpTools.form.post(url, params);
        } catch (HttpException e) {
            log.error(msg + " HTTP request exception.", e);
            throw new ServiceException(GeneralErrorCode.SMS_BALANCES_ERROR);
        }

        String[] words = split(response.trim());
        String code = words[0];

        String succ = config.getString("resultcode.success");

        if (code == null || !code.equals(succ)) {
            String desc = config.getString("resultcode.balances." + code, false);
            log.error(msg + " result code is {} - {}", code, desc);
            throw new ServiceException(GeneralErrorCode.SMS_BALANCES_ERROR);
        }

        return ConvertTools.toInteger(words[1]) / 10.0;
    }

    private String[] split(String text) {
        Pattern hash = Pattern.compile("#");
        return hash.split(text);
    }

}
